package com.atguigu.exer;

import org.testng.annotations.Test;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 练习3:获取文本上字符出现的次数,把数据写入文件
 *
 * 思路：
 * 1.遍历文本每一个字符
 * 2.字符出现的次数存在Map中
 *
 * Map<Character,Integer> map = new HashMap<Character,Integer>();
 * map.put('a',18);
 * map.put('你',2);
 *
 * 3.把map中的数据写入文件
 *
 */
public class WordCount1 {
    @Test
    public void test1(){
        BufferedReader bf= null;
        BufferedWriter bw = null;
        try {
            Map<Character, Integer> map = new HashMap<>();
            bf = new BufferedReader(new FileReader(new File("dbcp.txt")));
            int c = 0;
            while((c = bf.read()) != -1) {
                //int 还原 char
                char ch = (char) c;
                // 判断char是否在map中第一次出现
                if (map.get(ch) == null) {
                    map.put(ch, 1);
                } else {
                    map.put(ch, map.get(ch) + 1);
                }
            }

            bw = new BufferedWriter(new FileWriter(new File("word.txt")));

            Set<Map.Entry<Character,Integer>> entrySet = map.entrySet();
            for(Map.Entry<Character,Integer> entry : entrySet){
                switch (entry.getKey()){
                    case ' ':
                        bw.write("空格：" + entry.getValue());
                        break;
                    case '\t':
                        bw.write("Tab键：" + entry.getValue());
                        break;
                    case '\n':
                        bw.write("换行：" + entry.getValue());
                        break;
                    case '\r':
                        bw.write("回车：" + entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey() + "：" + entry.getValue());
                        break;
                }
                bw.newLine();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(bf != null) {
                try {
                    bf.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
